<template>
    <view class="address">
        <view class="detail_bg">
            <u-form
                :rules="addressRules"
                :model="addressForm"
                ref="form"
                :labelStyle="labelStyle"
                labelPosition="top"
            >
                <u-form-item
                    labelWidth="85"
                    label="收货人"
                    prop="consigneeName"
                >
                    <view class="formInput">
                        <u-input
                            placeholder="请输入姓名"
                            border="none"
                            fontSize="28rpx"
                            color="#333"
                            v-model="addressForm.consigneeName"
                            clearable
                        />
                    </view>
                </u-form-item>
                <u-form-item
                    labelWidth="85"
                    label="手机号码"
                    prop="consigneeMobile"
                >
                    <view class="formInput">
                        <u-input
                            placeholder="请输入联系方式"
                            border="none"
                            fontSize="28rpx"
                            color="#333"
                            v-model="addressForm.consigneeMobile"
                            clearable
                        />
                    </view>
                </u-form-item>
                <u-form-item
                    labelWidth="85"
                    label="所在地址"
                    clearable
                    prop="province"
                >
                    <view class="formInput" @click="open_add">
                        <view style="width: 560rpx">
                            <u-text
                                :text="
                                    addressForm.province
                                        ? addressForm.province +
                                          addressForm.city +
                                          addressForm.county
                                        : address
                                "
                                size="26rpx"
                                :color="
                                    addressForm.province ? '#333' : '#c0c4cc'
                                "
                            />
                        </view>
                        <u-icon size="28rpx" name="arrow-right" />
                    </view>
                    <!-- 城市选择器 -->
                    <u-picker
                        :show="show"
                        ref="uPicker"
                        :columns="columns"
                        @confirm="confirm"
                        @close="pickerClose"
                        cancelText="重置"
                        closeOnClickOverlay
                        @cancel="reset"
                        @change="changeHandler"
                    ></u-picker>
                </u-form-item>
                <u-form-item
                    labelWidth="85"
                    label="详细地址"
                    clearable
                    prop="address"
                >
                    <u-textarea
                        ref="textarea"
                        count
                        maxlength="40"
                        cursorSpacing="30"
                        fixed
                        :customStyle="textAreaCustomStyle"
                        v-model="addressForm.address"
                        placeholder="请输入您的详细地址"
                        border="surround"
                        height="226rpx"
                        placeholderStyle="font-size:28rpx;color:#c0c4cc;"
                    />
                </u-form-item>
                <u-form-item labelWidth='85' clearable>
					<view class="flex_wrap">
						<u-icon
							v-if="defaultAddress == 1"
						    name="/pages_shop1/static/img/shop/chose.png"
						    size="44rpx"
							@click="chenked(0)"
						/>
						<u-icon
							v-if="defaultAddress == 0"
						    name="/pages_shop1/static/img/order/notChoose.png"
						    size="44rpx"
							@click="chenked(1)"
						/>
						<u-text text="设为默认收货地址" bold size="36rpx" color="#333" margin="0 0 0 18rpx" />
					</view>
				</u-form-item>
            </u-form>
        </view>
        <view class="save" @click="to_save">保存</view>
    </view>
</template>

<script>
import { address } from "@/utils/address.js";
import { addAddress } from "@/api/shop.js";
export default {
    data() {
        return {
            defaultAddress: "1", //默认地址1
            labelStyle: {
                fontSize: "36rpx",
                color: "#333",
                fontWeight: "bold",
            },
            textAreaCustomStyle: {
                backgroundColor: "#fff",
                color: "#333",
                width: "100%",
                padding: "20rpx",
                paddingBottom: "40rpx",
                boxSizing: "border-box",
                fontSize: "26rpx",
            },
            //显示选择器
            show: false,
            columns: [],
            value: "",
            address: "选择省/市/区",
            origiData: address, //获取到的原始数据
            addressForm: {
                consigneeName: "", //姓名
                consigneeMobile: "", //手机号
                province: "", //省
                city: "", //市
                county: "", //区
                address: "", //详细地址
                defaultAddress: "", //是否默认
            },
            addressRules: {
                consigneeName: [{ required: true, message: "请填写姓名" }],
                province: [{ required: true, message: "请填写所在地址" }],
                address: [{ required: true, message: "请填写详细地址" }],
                consigneeMobile: [
                    {
                        type: "string",
                        required: true,
                        message: "请填写手机号",
                        trigger: ["blur", "change"],
                    },
                    {
                        validator: (rule, value, callback) => {
                            return this.$u.test.mobile(value);
                        },
                        message: "手机号格式不正确",
                        trigger: ["blur"],
                    },
                ],
            },
        };
    },
    mounted() {
        this.handelData();
    },
    onReady() {
        this.$refs.form.setRules(this.addressRules);
        this.$refs.textarea.setFormatter(this.formatter);
    },
    methods: {
        formatter(value) {
            if (value.length > 40) {
                return value.slice(0, 40);
            } else {
                return value;
            }
        },
        chenked(type) {
            //切换默认
            this.defaultAddress = type;
        },
        to_save() {
            //点击保存
            const that = this;
            this.$refs.form
                .validate()
                .then((res) => {
                    // uni.$u.toast('校验通过');
                    const params = {
                        // id : this.id,
                        consigneeName: that.addressForm.consigneeName, //名字
                        consigneeMobile: that.addressForm.consigneeMobile, //手机号
                        province: that.addressForm.province, //省
                        city: that.addressForm.city, //市
                        county: that.addressForm.county, //区
                        address: that.addressForm.address, //详细地址
                        defaultAddress: that.defaultAddress, //默认地址
                        addressPlatform: "2", //地址所属平台
                    };
                    addAddress(params).then((res) => {
                        uni.$u.toast("保存成功");
                        uni.$u.sleep(500).then(() => {
                             this.$store.dispatch("GET_ADDRESS_LIST");
								uni.setStorageSync("defullAddressId",res.data);
                            uni.navigateBack({
                                delta: 1,
                            });
                        });
                    });
                })
                .catch((errors) => {
                    // uni.$u.toast('校验失败');
                });
        },
        open_add() {
            this.show = true;
        },
        reset() {
            //重置按钮
            var _this = this;
            _this.addressForm.province = "";
            setTimeout(() => {
                _this.show = false;
            }, 500);
        },
        pickerClose() {
            this.show = false;
        },
        //初始化开始数据
        handelData() {
            let sheng = [];
            let shi = [];
            let qu = [];
            this.origiData.forEach((item) => {
                sheng.push(item.value);
                // 设置出初始化的数据
                if (item.value == "北京市") {
                    item.children.forEach((child) => {
                        shi.push(child.value);

                        if (child.value == "市辖区") {
                            child.children.forEach((el) => {
                                qu.push(el.value);
                            });
                        }
                    });
                }
            });
            this.columns.push(
                JSON.parse(JSON.stringify(sheng)),
                JSON.parse(JSON.stringify(shi)),
                JSON.parse(JSON.stringify(qu))
            );
        },
        changeHandler(e) {
            const {
                columnIndex,
                value,
                values, // values为当前变化列的数组内容
                index,
                // 微信小程序无法将picker实例传出来，只能通过ref操作
                picker = this.$refs.uPicker,
            } = e;
            // 当第一列值发生变化时，变化第二列(后一列)对应的选项
            if (columnIndex === 0) {
                // picker为选择器this实例，变化第二列对应的选项
                this.origiData.forEach((item) => {
                    if (value[0] == item.value) {
                        let shi = [];
                        let flag = item.children[0].value;
                        item.children.forEach((val, ol) => {
                            shi.push(val.value);
                            if (shi[0] == flag) {
                                //设置默认开关（选择省份后设置默认城市）
                                flag = "";
                                let qu = [];
                                val.children.forEach((vol) => {
                                    qu.push(vol.value);
                                });
                                picker.setColumnValues(2, qu);
                            }
                        });
                        picker.setColumnValues(1, shi);
                    }
                });
            }
            //当第二列变化时，第三列对应变化
            if (columnIndex === 1) {
                this.origiData.forEach((item) => {
                    if (value[0] == item.value) {
                        let shi = [];
                        item.children.forEach((val, ol) => {
                            shi.push(val.value);
                            if (value[1] == val.value) {
                                let qu = [];
                                val.children.forEach((vol) => {
                                    qu.push(vol.value);
                                });
                                picker.setColumnValues(2, qu);
                            }
                        });
                    }
                });
            }
        },
        // 确认选中的数据
        confirm(e) {
            this.addressForm.province = e.value[0];
            this.addressForm.city = e.value[1];
            this.addressForm.county = e.value[2];
            this.show = false;
        },
    },
};
</script>

<style lang="scss" scoped>
.address {
    background: #fff;
    width: 100%;
    height: 100vh;
    padding: 40rpx 28rpx 0;
}
.detail_bg {
    // height: 1026rpx;
    background: #eef2fa;
    border-radius: 20rpx;
    padding: 10rpx 28rpx 20rpx;
}
.save {
    width: 548rpx;
    height: 88rpx;
    background: #588bf3;
    border-radius: 44rpx;
    line-height: 88rpx;
    color: #fff;
    text-align: center;
    font-size: 36rpx;
    margin: 100rpx auto 0;
}
.formInput {
    width: 638rpx;
    height: 84rpx;
    background: #ffffff;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
}
</style>
